#include "stm32f10x.h"                  // Device header
#include "Countersensor.h"

uint16_t Counter = 0;

void Countersenor_Init(void)
{
	//使能APB2总线上GPIOB外设的时钟
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
	//不要忘记AFIO也是外设，也需要在RCC中启用AFIO的时钟
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
	//STM32, EXTI 外设不需要启用RCC使用
	//STM32, NVIC是内核外设，RCC管理不到，RCC是管理外部设备的
	
	//配置GPIOB_Pin12的工作模式
	GPIO_InitTypeDef GPIOInitStruture;
	GPIOInitStruture.GPIO_Mode = GPIO_Mode_IPU;
	GPIOInitStruture.GPIO_Pin = GPIO_Pin_14;
	GPIOInitStruture.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_Init(GPIOB, &GPIOInitStruture);
	
	//AFIO配置，EXTI外设中断源选择GPIO Pin
	GPIO_EXTILineConfig(GPIO_PortSourceGPIOB, GPIO_PinSource14);
	
	//EXTI配置，设置GPIO EXTI外设中断电平触发方式：上升沿/下降沿/双边沿
	EXTI_InitTypeDef EXTI_InitStruct;
	EXTI_InitStruct.EXTI_Line = EXTI_Line14;
	EXTI_InitStruct.EXTI_Mode = EXTI_Mode_Interrupt;
	EXTI_InitStruct.EXTI_Trigger = EXTI_Trigger_Falling;
	EXTI_InitStruct.EXTI_LineCmd = ENABLE;
	EXTI_Init(&EXTI_InitStruct);
	
	//NVIC配置，设置EXTI外设中断优先级
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
	
	NVIC_InitTypeDef NVIC_InitStruct;
	NVIC_InitStruct.NVIC_IRQChannel = EXTI15_10_IRQn;
	NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
	NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 0;
	NVIC_InitStruct.NVIC_IRQChannelSubPriority = 1;
	NVIC_Init(&NVIC_InitStruct);
	
}

uint16_t getCountersensor(void)
{
	return Counter;
}

void EXTI15_10_IRQHandler(void)
{
	static uint32_t lasttime;
	uint32_t currentTime = 0;
	if(EXTI_GetITStatus(EXTI_Line14) == SET){
		
		//currentTime = SysTick_Val;
		//if(currentTime - lasttime > 5000)	// 5ms消抖时间
		{
				/*如果出现数据乱跳的现象，可再次判断引脚电平，以避免抖动*/
			if (GPIO_ReadInputDataBit(GPIOB, GPIO_Pin_14) == 0){
				Counter++;
				lasttime = currentTime; 
			}
		}

		
		//一定要清除中断标志位，如果不清除中断标志位，就会一直触发中断
		EXTI_ClearITPendingBit(EXTI_Line14);
	}
}
